<template>
  <el-dialog
    v-model="dialogVisible"
    title="找回密码"
    width="500px"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :show-close="false"
    class="change-pwd-dialog"
  >
    <PhoneCode
      :submit-api="SystemApi.updatePwdByPhone"
      :send-code-api="SystemApi.sendSmsCodeRecoverPwd"
      :send-code-scene="3"
      :platform="PLATFORM"
      type="password"
      ref="PhoneCodeRef"
    ></PhoneCode>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submit">确认</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { FormInstance } from "element-plus";
import { watch } from "vue";
import { ref } from "vue";
import PhoneCode from "@/components/PhoneCode/index.vue";
import { reactive } from "vue";
import { SystemApi } from "@/api/modules";
import { PLATFORM } from "@/config";

const changePwdRef = ref<FormInstance>();
const PhoneCodeRef = ref<InstanceType<typeof PhoneCode> | null>(null);
const activeName = ref("password");

const form = ref({
  password: "",
  newPassword: "",
  confirmPassword: "",
});
const validatePass = (rule: any, value: any, callback: any) => {
  if (value === "") {
    callback(new Error("请输入新密码"));
  } else {
    if (form.value.confirmPassword !== "") {
      if (!changePwdRef.value) return;
      changePwdRef.value.validateField("confirmPassword", () => null);
    }
    callback();
  }
};
const validatePass2 = (rule: any, value: any, callback: any) => {
  if (value === "") {
    callback(new Error("请输入确认密码"));
  } else if (value !== form.value.newPassword) {
    callback(new Error("两次输入不一致!"));
  } else {
    callback();
  }
};
const formRules = reactive({
  newPassword: [
    { validator: validatePass, trigger: "blur" },
    { required: true, trigger: "blur", message: "请输入新密码" },
  ],
  confirmPassword: [
    { validator: validatePass2, trigger: "blur" },
    { required: true, trigger: "blur", message: "请输入确认密码" },
  ],
  password: [{ required: true, trigger: "blur", message: "请输入原始密码" }],
});

const dialogVisible = ref(false);
watch(dialogVisible, () => {
  changePwdRef.value?.resetFields();
  PhoneCodeRef.value?.phoneFormRef?.resetFields();
});
watch(activeName, () => {
  changePwdRef.value?.resetFields();
  PhoneCodeRef.value?.phoneFormRef?.resetFields();
});
const openDialog = () => {
  dialogVisible.value = true;
};
const submit = () => {
  PhoneCodeRef.value?.submit().then(() => {
    dialogVisible.value = false;
  });
};

defineExpose({ openDialog });
</script>
<style lang="scss">
.change-pwd-dialog.el-dialog {
  .el-dialog__header {
    padding-bottom: 0;
    border-bottom: none;
  }
}
</style>
